package com.clickpaas.governmentcloud.common;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Map;

@Slf4j
public class TokenCommon {
	
	public static boolean isTokenEffect(String jwt) {
	    if (StringUtils.isEmpty(jwt)) {
	        return false;
	    }
	    Map<String, Object> claims = verifyJavaWebToken(jwt);
	    if (null == claims) {
	    	log.info("转换jwt失败！");
	        return false;
	    }
	    return true;
	}
	
	public static Map<String, Object> verifyJavaWebToken(String jwt) {
	    try {
	    	String publicKeyStr = "8Q1E5ze+kEWPqtQaW7cVMrIzMnAIba8wj4bsUrmRmF2udcD5O2v3MfsZsd3owO2Nv/JQw0olsmMv";
	        Map<String, Object> jwtClaims =
	                Jwts.parser().setSigningKey(publicKeyStr).parseClaimsJws(jwt).getBody();
	        return jwtClaims;
	    } catch (ExpiredJwtException e) {
			log.info("Token超时,验证失败");
	        return null;
	    }catch (Exception e){
			log.info("Token转换jwt异常：【{}】",e);
			return null;
		}
	}
	
	public static String getCorpNameByToken(String token) {
		String publicKeyStr = "8Q1E5ze+kEWPqtQaW7cVMrIzMnAIba8wj4bsUrmRmF2udcD5O2v3MfsZsd3owO2Nv/JQw0olsmMv";
		isTokenEffect(token);
		Claims claims = Jwts.parser()
        .setSigningKey(publicKeyStr)   
        .parseClaimsJws(token)
        .getBody();
	    //log.info("claims: 【{}】",claims);
	    Object object = claims.get("jti");
	    Object sub = claims.get("sub");
	    JSONObject jsonObject = new JSONObject();
	    JSONObject subJson = JSONObject.parseObject(sub.toString());
	    String corpName = subJson.getString("corpName");
		log.info("公司名称: 【{}】",corpName);

	    return corpName;
	}

}
